﻿using System.Collections.Concurrent;

namespace VIA.Project.Domain.Command
{
    public interface ICommandExecutor
    {
        void AddCommandPanel(ICommandPanel commandPanel);
        void Regist(string id, Action<object> func);
        void Execute(string id, object cmd);
        void ClearTask();
    }

    public class CommandExecutor : ICommandExecutor
    {
        private List<ICommandPanel> commandPanels = new List<ICommandPanel>();
        public ConcurrentDictionary<string, Action<object>> Tasks { get; set; } = new ConcurrentDictionary<string, Action<object>>();
        public CommandExecutor() { }

        private void CommandReceived(object? sender, CommandReceivedEventArgs e)
        {
            Execute(e.ID, e.Command);
        }

        public void AddCommandPanel(ICommandPanel commandPanel)
        {
            commandPanel.CommandReceived -= CommandReceived;
            commandPanel.CommandReceived += CommandReceived;
            commandPanels.Add(commandPanel);
        }

        public void Regist(string id, Action<object> func)
        {
            if (!Tasks.TryAdd(id, func))
                Tasks[id] = func;
        }

        public void Execute(string id, object cmd)
        {
            if (!string.IsNullOrEmpty(id) && Tasks.TryGetValue(id, out Action<object> fuc))
            {
                Task.Run(() => { fuc(cmd); });
            }
        }

        public void ClearTask()
        {
            Tasks.Clear();
        }
    }
}
